package robotninja.asctec.test.imu;

import java.util.Date;
import java.util.HashMap;

import robotninja.driver.asctec.AsctecDriver;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

	/**
	 * Asctec Driver.
	 */
	AsctecDriver driver;
	private Activity act;
	private TextView tv;
	String s;

	// Need handler for callbacks to the UI thread
	final Handler mHandler = new Handler();

	// Create runnable for posting
	final Runnable mUpdateResults = new Runnable() {
		public void run() {
			updateResultsInUi();
		}

	};

	private void updateResultsInUi() {
		tv.setText(s);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		tv = (TextView) findViewById(R.id.textBox);

		act = this;

		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					// Connect
					driver = new AsctecDriver();
					driver.connect(getSerialParameters(act));

					for (int i = 0; i < 50000; i++) {
						// Get data
						double[] senseIMU = driver.senseIMU();
						if (senseIMU == null) {
							s = "Error";
							Thread.sleep(100);
							mHandler.post(mUpdateResults);
							continue;
						}

						s = ">> i=" + i + "\ng: " + senseIMU[0] + ", "
								+ senseIMU[1] + ", " + senseIMU[2]
								+ senseIMU[4] + "," + senseIMU[5] + "\na:"
								+ senseIMU[6] + "," + senseIMU[7] + ", "
								+ senseIMU[8] + "\np: " + senseIMU[9];

						String s2 = ">> i=" + i + " t="
								+ (new Date()).getTime() + " g: " + senseIMU[0]
								+ "," + senseIMU[1] + "," + senseIMU[2]
								+ " m: " + senseIMU[4] + "," + senseIMU[5]
								+ " a: " + senseIMU[6] + "," + senseIMU[7]
								+ "," + senseIMU[8];
						Log.d("IMU", s2);

						mHandler.post(mUpdateResults);
						Thread.sleep(100);
					}

				} catch (Exception e) {
					e.printStackTrace();
					// tv.setText(">>" + e.getMessage());
				}

			}
		});

		t.start();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private HashMap<String, Object> getSerialParameters(Activity act) {
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("Activity", act);
		params.put("baudrate", 57600);
		params.put("dataBits", 8);
		params.put("stopBits", 1);
		params.put("parity", 0);

		return params;
	}
}
